package com.hsy.swu.home.leftdrawer

import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.View.OnClickListener
import android.widget.TextView
import androidx.core.view.forEachIndexed
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.room.Room
import com.hsy.swu.R
import com.hsy.swu.clouddb.MyUser
import com.hsy.swu.databinding.ActivityAddCustomCourseBinding
import com.hsy.swu.home.course.CourseModel
import com.hsy.swu.hsyutils.HsyActivity
import com.hsy.swu.hsyutils.HsyViewModel
import com.hsy.swu.hsyutils.MActivityUtil
import com.hsy.swu.roomdb.AppDatabase
import com.hsy.swu.roomdb.CourseDao
import com.kongzue.dialogx.customwheelpicker.CustomWheelPickerDialog
import com.kongzue.dialogx.customwheelpicker.interfaces.OnCustomWheelPickerSelected
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.dialogs.InputDialog
import com.kongzue.dialogx.interfaces.OnBindView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class AddCustomCourseActivity : HsyActivity<ActivityAddCustomCourseBinding, HsyViewModel>() {
    private val crtUser = MyUser.currentUser
    private lateinit var courseDao: CourseDao

    private lateinit var mDayPickerDialog: CustomWheelPickerDialog
    private lateinit var mSectionPickerDialog: CustomWheelPickerDialog
    private lateinit var mWeekPickerDialog: CustomWheelPickerDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        refreshWhenWeekChangedObserver()

        setClick()

        courseDao = Room.databaseBuilder(
            this,
            AppDatabase::class.java,
            "swu"
        ).build().courseDao()
    }

    override fun onResume() {
        super.onResume()
        mBinding.root.post {
            getCourseFromRoomDBAndRefreshUI()
        }
    }

    private fun setClick() {
        val onWeekPickerClickListener = OnClickListener {
            val startWeek = mBinding.courseTableViewGroup.currentWeek.value ?: 1
            CustomWheelPickerDialog.build()
                .setTitle("请选择周数")
                .addWheel((1..20).map { "第 $it 周" }.toTypedArray())
                .setDefaultSelect(0, startWeek - 1)
                .setOnWheelChangeListener { _, _, _, index, _ ->
                    mBinding.courseTableViewGroup.currentWeek.postValue(index + 1)
                }
                .show(object : OnCustomWheelPickerSelected() {
                    override fun onSelected(
                        p0: CustomWheelPickerDialog?,
                        p1: String?,
                        p2: Array<out String>?,
                        p3: IntArray?
                    ) {
                    }
                })
        }
        mBinding.week.setOnClickListener(onWeekPickerClickListener)
        mBinding.btnExpand.setOnClickListener(onWeekPickerClickListener)

        mBinding.btnAdd.setOnClickListener {
            startAddCourseChain()
        }

        mBinding.btnDel.setOnClickListener {
            onDelCourseClick()
        }
    }

    private fun refreshWhenWeekChangedObserver() {
        mBinding.courseTableViewGroup.let { viewGroup ->
            viewGroup.currentWeek.observe(this) {
                viewGroup.checkCourseIsInWeek(it)
                mBinding.apply {
                    week.text = "第 $it 周"
                    month.text = "${viewGroup.dateList[it * 7 - 1].second}" // 获取当前看的这周的周日的月份
                    linearDayValue.forEachIndexed { index, tv ->
                        // 第一个 TextView不是显示日期的，所以跳过
                        if (index != 0)
                            (tv as TextView).text =
                                "${viewGroup.dateList[(it - 1) * 7 + index - 1].third}"
                    }
                }
            }
        }
    }

    private fun getCourseFromRoomDBAndRefreshUI() {
        lifecycleScope.launch {
            mBinding.name.text = crtUser.nickName
            val courseDBList: List<CourseModel>
            val customCourseList: List<CourseModel>
            withContext(Dispatchers.IO) {
                courseDBList = courseDao.getAllByAccount(crtUser.account)
                customCourseList = courseDao.getAllCustomCourse()
            }
            mBinding.courseTableViewGroup.apply {
                courseList = courseDBList.toMutableList().apply {
                    addAll(customCourseList)
                }
                removeAllViews()
            }
        }
    }

    private fun startAddCourseChain() {
        val toAddCourse = CourseModel()
        setCourseName(toAddCourse)
    }

    private fun setCourseName(toAddCourse: CourseModel) {
        InputDialog.build()
            .setTitle("请输入课程名称")
            .setOkButton("确认") { _, _, inputStr ->
                toAddCourse.courseName = inputStr
                setClassRoom(toAddCourse)
                return@setOkButton false
            }
            .show()
    }

    private fun setClassRoom(toAddCourse: CourseModel) {
        InputDialog.build()
            .setTitle("请输入教室")
            .setOkButton("确认") { _, _, inputStr ->
                toAddCourse.classRoom = inputStr
                pickDay(toAddCourse)
                return@setOkButton false
            }
            .show()
    }

    private fun pickDay(toAddCourse: CourseModel) {
        mDayPickerDialog = CustomWheelPickerDialog()
        mDayPickerDialog.apply {
            setTitle("请选择星期几")
            addWheel((1..7).map {
                "星期${
                    when (it) {
                        1 -> "一"
                        2 -> "二"
                        3 -> "三"
                        4 -> "四"
                        5 -> "五"
                        6 -> "六"
                        7 -> "日"
                        else -> throw IllegalStateException("星期几写错了")
                    }
                }"
            }.toTypedArray())
            show(object : OnCustomWheelPickerSelected() {
                override fun onSelected(
                    p0: CustomWheelPickerDialog?,
                    p1: String?,
                    p2: Array<out String>?,
                    p3: IntArray?
                ) {
                    toAddCourse.dayOfWeek = mDayPickerDialog.getWheelSelectedIndex(0) + 1
                    pickSection(toAddCourse)
                }
            })
        }
    }

    private fun pickSection(toAddCourse: CourseModel) {
        mSectionPickerDialog = CustomWheelPickerDialog()
        mSectionPickerDialog.apply {
            setTitle("请选择起始和结束课时")
            addWheel((1..14).map { "第 $it 节" }.toTypedArray())
            addWheel((1..14).map { "第 $it 节" }.toTypedArray())
            show(object : OnCustomWheelPickerSelected() {
                override fun onSelected(
                    p0: CustomWheelPickerDialog?,
                    p1: String?,
                    p2: Array<out String>?,
                    p3: IntArray?
                ) {
                    if (p3?.get(1)!! >= p3[0]) {
                        toAddCourse.section =
                            "${mSectionPickerDialog.getWheelSelectedIndex(0) + 1}-" +
                                    "${mSectionPickerDialog.getWheelSelectedIndex(1) + 1}"
                        pickWeek(toAddCourse)
                    } else {
                        pickSection(toAddCourse)
                        MActivityUtil.showToast("选择有误，请重选")
                    }
                }
            })
        }
    }

    private fun pickWeek(toAddCourse: CourseModel) {
        val startWeek = mBinding.courseTableViewGroup.currentWeek.value ?: 1
        mWeekPickerDialog = CustomWheelPickerDialog()
        mWeekPickerDialog.apply {
            setTitle("请选择起始和结束周")
            addWheel((1..20).map { "第 $it 周" }.toTypedArray())
            addWheel((1..20).map { "第 $it 周" }.toTypedArray())
            setDefaultSelect(hashMapOf(0 to startWeek - 1, 1 to startWeek - 1))
            show(object : OnCustomWheelPickerSelected() {
                override fun onSelected(
                    p0: CustomWheelPickerDialog?,
                    p1: String?,
                    p2: Array<out String>?,
                    p3: IntArray?
                ) {
                    if (p3?.get(1)!! >= p3[0]) {
                        toAddCourse.studyWeek =
                            "${mWeekPickerDialog.getWheelSelectedIndex(0) + 1}-" +
                                    "${mWeekPickerDialog.getWheelSelectedIndex(1) + 1}周"
                        addCourse(toAddCourse)
                    } else {
                        pickWeek(toAddCourse)
                        MActivityUtil.showToast("选择有误，请重选")
                    }
                }
            })
        }
    }

    private fun addCourse(toAddCourse: CourseModel) {
        toAddCourse.classification = "custom"
        lifecycleScope.launch {
            withContext(Dispatchers.IO) {
                courseDao.insertAll(listOf(toAddCourse))
            }
            getCourseFromRoomDBAndRefreshUI()
        }
    }

    private fun onDelCourseClick() {
        lifecycleScope.launch {
            val allCustomCourse = withContext(Dispatchers.IO) {
                courseDao.getAllCustomCourse()
            }
            if (allCustomCourse.isEmpty()) {
                MActivityUtil.showToast("还没有自定义添加的课程噢")
                return@launch
            }
            val menuList = mutableListOf<CourseModel>()
            allCustomCourse.forEach {
                menuList.add(it)
            }

            CustomDialog.build()
                .setCustomView(object :
                    OnBindView<CustomDialog?>(R.layout.layout_del_custom_course) {
                    override fun onBind(dialog: CustomDialog?, v: View) {
                        val rv = v.findViewById<RecyclerView>(R.id.recyclerView)
                        rv.apply {
                            adapter = DelCustomCourseAdapter().apply {
                                customCourseList = menuList
                                setDelClickListener { position ->
                                    lifecycleScope.launch {
                                        withContext(Dispatchers.IO) {
                                            courseDao.deleteCustomCourseByName(customCourseList[position].courseName)
                                        }
                                        val tempList = customCourseList.toMutableList()
                                        tempList.removeAt(position)
                                        customCourseList = tempList

                                        notifyDataSetChanged()
                                        getCourseFromRoomDBAndRefreshUI()
                                    }
                                }
                            }
                            layoutManager = LinearLayoutManager(v.context)
                        }
                    }
                })
                .setAlignBaseViewGravity(
                    mBinding.btnDel,
                    Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL
                )
                .show()
        }
    }
}